<!-- 编辑+新增活动+协办方查看活动配置 -->
<template>
  <a-spin tip="加载中..." :spinning="loading" wrapperClassName="spinning">
    <div class="anchor">
      <h6>填写导航</h6>
      <a-anchor :target-offset="targetOffset">
        <a-anchor-link href="#BasicInfo" title="基础信息" />
        <a-anchor-link href="#Particulars" title="活动介绍" />
        <a-anchor-link href="#TicketSet" title="报名设置" />
        <a-anchor-link href="#ActivityForm" title="收集表单" />
        <a-anchor-link href="#operationalTools" title="运营设置" />
        <a-anchor-link href="#Configuration" title="其它设置" />
      </a-anchor>
    </div>

    <div class="editActivity-container">
      <BasicInfo
        id="BasicInfo"
        :info="activityInfo"
        @changePublishStatus="changePublishStatus"
        ref="basicInfoRef"
        @update="updateActivityInfo"
      />
      <Particulars
        id="Particulars"
        :info="activityInfo"
        @changePublishStatus="changePublishStatus"
        ref="particularsRef"
      >
      </Particulars>

      <TicketSet
        id="TicketSet"
        ref="ticketSetRef"
        :info="activityInfo"
        :endTime="endTime"
        :startTime="startTime"
        :maxNum="maxNum"
        :enrollRestrict="enrollRestrict"
      ></TicketSet>

      <activityForm id="ActivityForm" ref="activityFormRef" :activityInfo="activityInfo"> </activityForm>

      <OperationalTools id="operationalTools" ref="operationalToolsRef" :info="activityInfo"></OperationalTools>

      <Configuration id="Configuration" :info="activityInfo" ref="configurationRef" />

      <ManyConfirmModal ref="ManyConfirmModal" />

      <DashboardGuide />

      <!-- 分享活动 -->
      <ShareModal ref="ShareModal" />

      <div class="footer">
        <a-button @click="handlePreview">保存并预览活动</a-button>
        <a-button v-if="!disableEditing" type="primary" ghost @click="() => handleSaveActivity()">保存活动</a-button>
        <a-button
          v-if="!disableEditing && activityInfo.publishStatus !== publishStatusEnum.ISSUE"
          type="primary"
          @click="verifyIssue"
          :disabled="loading"
        >
          发布活动
        </a-button>
      </div>
    </div>
  </a-spin>
</template>

<script>
import BasicInfo from './basicInfo.vue'
import Particulars from './particulars.vue'
import Configuration from './configuration.vue'
import TicketSet from './TicketSet/index.vue'
import OperationalTools from './operationalTools.vue'
import { getUnionActivityInfo } from '@/api/activity/activity'
import {
  activityTypeEnum,
  publishStatusEnum,
  ActivitySettlementStatusEnum,
  StockLimitEnum,
  BuyTimeTypeEnum
} from '@/enums/activity'
import {
  createUnionActivity,
  editUnionActivity,
  createDetailsQrcode,
  getUnionActivityTicketList
} from '@/api/activity/activity'
import { actconfigAdd } from '@/api/activity/sign'
import { TENANTID } from '@/store/mutation-types'
import Vue from 'vue'
import ManyConfirmModal from '@/components/ManyConfirmModal'
import ShareModal from '@/components/ShareModal/index.vue'
import { cancelActivityErr } from '@/utils/codes'
import DashboardGuide from '../../components/DashboardGuide/index.vue'
import activityForm from './activityForm/index.vue'
import moment from 'moment'
export default {
  components: {
    BasicInfo,
    ShareModal,
    Particulars,
    Configuration,
    TicketSet,
    OperationalTools,
    ManyConfirmModal,
    DashboardGuide,
    activityForm
  },
  async mounted() {
    await this.getActivityInfo() // 获取活动详情
    await this.queryActivityTicketList()
  },
  data() {
    return {
      publishStatusEnum,
      current: 0,
      activityInfo: {},
      loading: false,
      targetOffset: 150,
      enrollRestrict: 0,
      maxNum: 0,
      endTime: '',
      startTime: '',
      display: undefined
    }
  },
  computed: {
    disabled() {
      return this.activityInfo.activityType === 'other_join' // 协办方
    },
    disableEditing() {
      return (
        [
          ActivitySettlementStatusEnum.PROGRESS,
          ActivitySettlementStatusEnum.SUCCESS,
          ActivitySettlementStatusEnum.PART_SUCCESS
        ].includes(this.activityInfo.settleStatus) || this.disabled
      )
    }
  },
  methods: {
    updateActivityInfo(info) {
      this.maxNum = info.maxNum
      this.enrollRestrict = info.enrollRestrict
      this.endTime = info.endTime
      this.startTime = info.startTime
    },
    async getActivityInfo() {
      const { activityId } = this.$route.query
      if (!activityId) return

      this.loading = true
      try {
        const { data } = await getUnionActivityInfo(activityId)
        this.activityInfo = data
        this.maxNum = data.maxNum
        this.enrollRestrict = data.enrollRestrict
        this.endTime = data.endTime
        this.$route.meta.title = data.activityType === activityTypeEnum.other_join ? '活动配置' : '编辑活动'
      } finally {
        this.loading = false
      }
    },
    changePublishStatus(val) {
      this.activityInfo.publishStatus = val
    },
    async handleSave(params) {
      return new Promise(async (resolve, reject) => {
        try {
          this.loading = true

          const { data, code, msg } = params.id ? await editUnionActivity(params) : await createUnionActivity(params)

          if (code === cancelActivityErr) {
            this.$warning({
              title: '活动保存配置成功',
              width: 600,
              content: h => {
                return h('div', [
                  h('p', '活动保存配置成功！以下配置异常，更改失败！：'),
                  h(
                    'div',
                    {
                      style: {
                        padding: '9px 16px',
                        background: '#E8FFEA'
                      }
                    },
                    [
                      JSON.parse(msg).map((item, index) => {
                        return h('p', `报名类型：【${item}】 删除失败，原因：已有用户报名，无法删除；`)
                      })
                    ]
                  )
                ])
              },
              onOk: () => {
                resolve()
              }
            })
            return
          }

          if (code) reject('保存失败')

          // 编辑成功
          if (params.id && data) {
            resolve()
            return
          }

          actconfigAdd({
            activityId: data,
            activityName: params.title,
            signName: '签到码',
            assocTenantId: Vue.ls.get(TENANTID),
            printStyle: 2
          })

          await this.$router.push({
            path: '/activity/activityUpdate',
            query: { ...this.$route.query, activityId: data, timestamp: Date.now() }
          })
          resolve()
        } catch (err) {
          reject(err)
        } finally {
          this.loading = false
        }
      })
    },
    async refresh() {
      await this.getActivityInfo()
      this.$refs.particularsRef.init()
      this.queryActivityTicketList()
    },

    async handleSaveActivity(issue) {
      const basicInfoData = await this.$refs.basicInfoRef.saveForm()
      const particularsData = await this.$refs.particularsRef.saveForm()
      const configurationData = this.$refs.configurationRef.saveForm()
      const ticketSet = await this.$refs.ticketSetRef.saveForm()
      const customForm = await this.$refs.activityFormRef.saveForm()
      const operationalTools = await this.$refs.operationalToolsRef.saveForm()

      ticketSet.ticketTypeConfigList.forEach((element, index) => {
        const maxDate =
          basicInfoData.enrollTimeType === BuyTimeTypeEnum.activityEndTime
            ? basicInfoData.endTime
            : basicInfoData.enrollEndTime
        const minDate =
          basicInfoData.enrollTimeType === BuyTimeTypeEnum.activityEndTime
            ? this.activityInfo.createTime || moment().format('YYYY-MM-DD HH:mm:00')
            : basicInfoData.enrollStartTime

        if (element.buyTimeType === BuyTimeTypeEnum.custom) {
          if (element.startTime) {
            /**票报名开始时间在活动报名开始时间之前 */
            if (moment(minDate).isAfter(moment(element.startTime).format('YYYY-MM-DD HH:mm'))) {
              element.startTime = minDate
            }
            /**票报名开始时间在活动报名结束时间之后 */
            if (moment(element.startTime).isAfter(moment(maxDate).format('YYYY-MM-DD HH:mm'))) {
              element.startTime = minDate
            }
          }

          if (element.endTime) {
            /**票报名结束时间在活动报名开始时间之前 */
            if (moment(minDate).isAfter(moment(element.endTime).format('YYYY-MM-DD HH:mm'))) {
              element.endTime = maxDate
            }

            /**票报名结束时间在活动报名结束时间之后 */
            if (moment(element.endTime).isAfter(moment(maxDate).format('YYYY-MM-DD HH:mm'))) {
              element.endTime = maxDate
            }
          }

          if (!element.startTime) {
            element.startTime = minDate
          }
          if (!element.endTime) {
            element.endTime = maxDate
          }
        } else {
          element.startTime = minDate
          element.endTime = maxDate
        }
      })

      const params = {
        ...basicInfoData,
        detailList: particularsData,
        ...configurationData,
        ...ticketSet,
        customForm,
        ...operationalTools,
        ...issue
      }

      await this.handleSave(params)
      await this.refresh()
      issue || this.$message.success('活动保存成功')
    },
    async verifyIssue() {
      this.$confirm({
        title: '发布活动',
        width: 500,
        content: h => {
          return h('div', [
            h('p', '报名是否要立即发布活动？发布后用户可参与。'),
            h(
              'a-checkbox',
              {
                on: {
                  value: this.display === 1,
                  change: e => {
                    this.display = e.target.checked ? 1 : undefined
                  }
                }
              },
              [
                h('span', '活动暂不对外展示；'),
                h(
                  'p',
                  {
                    style: {
                      color: '#969799'
                    }
                  },
                  '(可在【活动管理】-【更多操作】中重新开启对外展示)'
                )
              ]
            )
          ])
        },
        okText: `立即发布`,
        cancelText: '继续编辑',
        centered: true,
        onOk: () => {
          return new Promise(async (resolve, reject) => {
            try {
              await this.handleSaveActivity({
                publishStatus: publishStatusEnum.ISSUE,
                display: this.display
              })
              this.refresh()
              this.$emit('changePublishStatus', publishStatusEnum.ISSUE)
              this.openManyConfirmModal()
              resolve()
            } catch (error) {
              reject(error)
              return
            }
          })
        }
      })
    },
    openManyConfirmModal() {
      this.$refs.ManyConfirmModal.open({
        title: '发布成功',
        content: '活动已发布成功，快去分享邀请用户来参会吧~',
        btns: [
          {
            text: '活动管理',
            props: {
              type: 'default'
            },
            onClick: () => {
              this.$router.replace({
                path: '/activity/activityDetail',
                query: {
                  activityId: this.$route.query.activityId
                }
              })
              this.$refs.ManyConfirmModal.handleCancel()
            }
          },
          {
            text: '分享活动',
            props: {
              type: 'primary'
            },
            onClick: () => {
              this.$refs.ShareModal.openModel(this.activityInfo.id, this.activityInfo.title)
              this.$refs.ManyConfirmModal.handleCancel()
            }
          }
        ]
      })
    },
    async handlePreview() {
      await this.handleSaveActivity()
      this.$router.push({
        name: 'activityDetailsPreview',
        query: {
          activityId: this.$route.query.activityId
        }
      })
    },
    async queryActivityTicketList() {
      if (!this.$route.query.activityId) return
      const res = await getUnionActivityTicketList({ activityId: this.$route.query.activityId })
      this.activityInfo.ticketTypeConfigList = res.data.map(item => {
        item.stockNum = item.stockLimit == StockLimitEnum.NO ? '' : String(item.stockNum)
        return item
      })
    }
  }
}
</script>

<style lang="less" scoped>
.spinning {
  ::v-deep .anchor {
    position: fixed;
    top: 150px;
    right: 50px;
    z-index: 999;
    background: white;
    box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    width: 140px;
    padding: 20px;

    h6 {
      font-weight: bold;
    }

    .ant-anchor-wrapper {
      background: transparent;
      margin-top: 15px;
    }
  }

  ::v-deep .ant-spin {
    position: fixed;
  }

  ::v-deep .ant-spin-container {
    .editActivity-container {
      padding-bottom: 100px;
      background: transparent;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .footer {
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        padding: 16px 20px;
        background-color: white;
        border-top: 1px solid #e5e6eb;
        display: flex;
        justify-content: center;
        gap: 8px;
        z-index: 8;
      }
    }
  }
}
</style>
